package com.bawei.weekone2207a.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

/**
 * 作者：赵亮
 * 时间：2024/12/14 9:31
 * 功能：ViewModel的封装
 */
abstract class BaseViewModel : ViewModel() {

    // 存储意图的channel
    private val _channel = Channel<IUiIntent>(Channel.UNLIMITED)

    // 页面状态
    val uiState = MutableStateFlow<UiState>(OnLoading)

    // 消费意图
    init {
        viewModelScope.launch {
            _channel.receiveAsFlow().collect {
                handIntent(it)
            }
        }
    }

    abstract fun handIntent(it: IUiIntent)

    // 生产意图
    fun sendIntent(iUiIntent: IUiIntent) {
        viewModelScope.launch {
            _channel.send(iUiIntent)
        }
    }

    // 网络请求
    fun httpRequest(flow: Flow<*>) {
        viewModelScope.launch {
            flow.flowOn(Dispatchers.IO)
                .catch { uiState.value = OnError(it.message.toString()) }
                .collect{ uiState.value = OnSuccess(it) }
        }
    }
}